<template>
  <div ref="artRef" class="w-full h-full" :style="{
    width: containerWidth,
    height: containerHeight,
    position: 'absolute',top: '0',
    left: '0'}"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import Artplayer from 'artplayer'
import Hls from 'hls.js'
import {imgUrl} from "@/utils/http.js";
import {mitter} from "@/eventbus/eventBus.js"

const artRef = ref(null)
let art = null
let currentHls = null

// 添加props接收父组件传入的尺寸
const props = defineProps({
  containerWidth: {
    type: String,
    default: '100%'  // 默认保持全宽
  },
  containerHeight: {
    type: String,
    default: '100%'  // 默认保持全高
  }
})

// 销毁播放器的方法
const destroyPlayer = () => {
  if (art) {
    art.destroy()
    art = null
  }
  if (currentHls) {
    currentHls.destroy()
    currentHls = null
  }
}

// 初始化播放器的方法
const initPlayer = (url) => {
  destroyPlayer() // 先销毁旧的实例
  art = new Artplayer({
    container: artRef.value,
    url: imgUrl+'video/'+url+'/index.m3u8',
    customType: {
      m3u8: (video, url) => {
        if (Hls.isSupported()) {
          const hls = new Hls()
          hls.loadSource(url)
          hls.attachMedia(video)
          hls.on(Hls.Events.ERROR, (event, data) => {
            console.error('HLS播放错误:', data)
          })
        } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
          video.src = url
        }
      }
    },
    theme: '#23ade5',
    volume: 0.7,
    isLive: false,// 是否是直播
    muted: false, // 设置视频为静音
    autoplay: true,// 自动播放
    pip: true,// 画中画
    autoSize: true,// 自动全屏
    autoMini: true,// 自动小屏
    screenshot: true,// 截图
    setting: true,// 设置
    loop: false,// 循环播放
    flip: true,// 画面翻转
    playbackRate: true,// 播放速度
    aspectRatio: false,// 宽高比
    fullscreen: true,// 全屏
    fullscreenWeb: true,// 网页全屏
    subtitleOffset: true,// 字幕偏移
    miniProgressBar: true,// 迷你进度条
    mutex: true,// 互斥
    backdrop: true,// 背景遮罩
    playsInline: true,// 画中画
    autoPlayback: true,// 自动播放
    airplay: true,// 投屏
  })
}
// 事件监听（使用once确保单次绑定）
const setupEventListener = () => {
  mitter.on('playUrl', handlePlayUrl)
}

// 移除事件监听
const removeEventListener = () => {
  mitter.off('playUrl', handlePlayUrl)
}

// 处理播放URL变化
const handlePlayUrl = (url) => {
  initPlayer(url)
}

onMounted(() => {
  setupEventListener()
})

onUnmounted(() => {
  destroyPlayer()
  removeEventListener()
})
</script>
